import Vue from 'vue'

import VueRouter from 'vue-router'
import axios from 'axios'


Vue.use(VueRouter)

import Home from '../pages/home.vue'
import Cart from '../pages/cart.vue'
import User from '../pages/user.vue'
import Login from '../pages/login.vue'
import Reg from '../pages/reg.vue'
import GoodsDil from '../pages/goodsdil.vue'
import NoPage from '../pages/nopage.vue'
import Search from '../pages/search.vue'
import List from '../pages/list.vue'
import Setting from '../pages/setting.vue'
import Service from '../pages/service.vue'



let router = new VueRouter({ //插件路由对象
	routes: [],
	mode: 'history',
	scrollBehavior() {
		// return 期望滚动到哪个的位置
		return {
			x: 0,
			y: 0
		}
	}
});


let data = [{
		path: '/home',
		component: Home,
		meta:"首页",
	},
	{
		path: '/search',
		component: Search,
		meta:"搜索",
	}, {
		path: '/cart',
		component: Cart,
		meta:"购物车",
	},
	{
		path: '/login',
		component: Login,
		meta:"登录",
	},
	{
		path: '/service',
		component: Service,
		meta:"客服",
	},
	{
		path: '/reg',
		component: Reg,
		meta:"注册",
	}, {
		path: '/user',
		component: User,
		meta:"会员中心"
	},
	{
		path: '/goodsdil/:id',
		component: GoodsDil,
		meta:"商品详情",
	},
	{
		path: '/setting',
		component: Setting,
		meta:"设置",
	},
	{
		path: '/list',
		component: List,
		meta:"分类列表"
	},
	{
		path: '/',
		redirect: '/home',
	},

	{
		path: '*',
		component: NoPage,
		meta:"404"
	},

]
router.addRoutes(data)

// 全局前置守卫
router.beforeEach((to, from, next) => {
	let path = to.path;
	if (/setting|login|reg|search/.test(path)) {
		next()
	} else {
		//准备集合
		let data = {}
		if (/home/.test(path)) {
			data = {
				url: "/goods",
				params: {
					_limit: 9,
					_sort:"proid"
				}
			}
		} else if (/list/.test(path)) {
			data = {
				url: "/goods",
				params: {
					_q: "",
				}
			}
		} else if (/cart/.test(path)) {
			let username =""
			if(JSON.parse(window.localStorage.getItem('user'))){
				username=JSON.parse(window.localStorage.getItem('user')).data.username
			}else{
				next("/login")
			}
			data ={
				url:"/cart",
				params:{
					username,
				}
			}
		} else if (/user|service/.test(path)) {
			data ={
				url:"/user",
			}
		} else if (/goodsdil/.test(path)) {
			let id=to.params.id
			data ={
				url:"/goods/"+id,
			}
		}
		axios(data).then(res => {
			if (res.err === 2 && !to.path.includes('/login')) {
				next("/login")
			} else if (res.err === 1) {
				to.query.data = res;
				next(); 
			} else{
				to.query.data = res.data;
				next()
			}
		})
	}
})

export default router
